package com.example.listenmailforfsbot.util;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

public class TextFilter {

    private String regex = "</br>";

    private Map<String,String> map = new HashMap<>();

//    static {
//        map.put("exceed concurrency limit"," 存在实时直播线路不足的报错 ");
//        map.put("the max byte size of text is 1000", " 存在moyin tts字数生成超限的报错 ");
//    }

    public TextFilter(String textFilterRegex, Map<String, String> map) {
        this.regex = textFilterRegex;
        this.map = map;
    }

    public String checkText(String text){

        System.out.println("待过滤文本:" + text);
        String[] strings = text.split(regex);
        StringBuilder res = new StringBuilder();

        for (String string : strings) {

            if(StringUtils.isBlank(string)){
                continue;
            }

            for (Map.Entry<String, String> entry : map.entrySet()) {
                if (string.contains(entry.getKey())) {
                    string = entry.getValue();
                    System.out.println("已替换" + entry.getKey());
                }
            }

            // 使用 Jsoup 解析 HTML
            Document doc = Jsoup.parse(string);
            //提取 全部文本
            res.append(doc.text());

        }

        for(Map.Entry<String, String> entry: map.entrySet() ){
            if(res.toString().contains(entry.getValue())){
                res = new StringBuilder(res.toString().replaceAll(entry.getValue(), ""));
                res.append("  相关报错已替换: ").append(entry.getValue());
                System.out.println("已整理" + entry.getValue());
            }
        }

        System.out.println("文本过滤替换结束,Time:\n\t\t" + LocalDateTime.now());
        System.out.println("处理后文本:" + res);
        return res.toString();

    }

    @Override
    public String toString() {
        return "TextFilter{" + "\n" +
                "\t\tregex='" + regex + '\'' + "\n" +
                "\t\tmap=" + map + "\n" +
                "\t}";
    }
}
